package net.csdn.business.notify.handler.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.config.AsyncThreadPoolConfig;
import net.csdn.business.notify.common.enums.ResultCodeEnum;
import net.csdn.business.notify.common.exception.BusinessException;
import net.csdn.business.notify.common.mapper.NotifyPrivateLetterMapper;
import net.csdn.business.notify.common.model.entity.NotifyPrivateLetter;
import net.csdn.business.notify.common.model.query.NotifyPrivateLetterQuery;
import net.csdn.business.notify.common.model.vo.NotifyPrivateLetterVO;
import net.csdn.business.notify.common.model.vo.UserInfoVO;
import net.csdn.business.notify.common.model.vo.UserPrivateLetterVO;
import net.csdn.business.notify.handler.service.INotifyPrivateLetterService;
import net.csdn.business.notify.feign.SystemFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;


/**
 * 通知中心-用户私信Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-27
 */
@Slf4j
@Service
public class NotifyPrivateLetterServiceImpl extends ServiceImpl<NotifyPrivateLetterMapper, NotifyPrivateLetter> implements INotifyPrivateLetterService
{

    @Resource(name= AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    private ThreadPoolTaskExecutor asyncExecutor;

    @Autowired
    private SystemFeignClient userFeignClient;

    /**
     * 分页查询通知中心-用户私信列表
     *
     * @param query 通知中心-用户私信
     * @return 通知中心-用户私信
     */
    @Override
    public Page<NotifyPrivateLetterVO> findPageList(NotifyPrivateLetterQuery query) {
        //获得Page对象
        Page<NotifyPrivateLetterVO> page = query.getPage();
        List<NotifyPrivateLetterVO> pageList=baseMapper.findPageList(page,query);
        if(pageList!=null&&pageList.size()>0){
            List<String> userIds=new ArrayList<>();
            pageList.stream().forEach(privateLetterVO->{
                String senderId=privateLetterVO.getSenderId();
                String receiverId=privateLetterVO.getReceiverId();
                userIds.add(senderId);
                userIds.add(receiverId);
            });
            try {
                Future<Map<String, UserInfoVO>> taskA =asyncExecutor.submit(()->{
                    //批量查询用户信息
                    Map<String, UserInfoVO> userInfoMap=new HashMap<>();
                    try {
                        userInfoMap=userFeignClient.batchQuery(userIds);
                    }catch (Exception e){
                        log.info("query remote user info error");
                    }
                    return userInfoMap;
                });
                Map<String, UserInfoVO> finalUserInfoMap = taskA.get();
                pageList.stream().parallel().forEach(privateLetterVO->{
                    String senderId=privateLetterVO.getSenderId();
                    String receiverId=privateLetterVO.getReceiverId();
                    UserInfoVO senderInfo = finalUserInfoMap.get(senderId);
                    if(senderInfo!=null){
                        privateLetterVO.setSenderName(senderInfo.getUsername());
                        privateLetterVO.setSenderPhoto(senderInfo.getPhoto());
                    }
                    UserInfoVO receiverInfo = finalUserInfoMap.get(receiverId);
                    if(receiverInfo!=null){
                        privateLetterVO.setSenderName(receiverInfo.getUsername());
                        privateLetterVO.setSenderPhoto(receiverInfo.getPhoto());
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询通知中心-用户私信
     * 
     * @param id 通知中心-用户私信主键
     * @return 通知中心-用户私信
     */
    @Override
    public NotifyPrivateLetterVO selectNotifyPrivateLetterById(String id)
    {
        NotifyPrivateLetterVO notifyPrivateLetterVO=baseMapper.selectNotifyPrivateLetterById(id);
        if(notifyPrivateLetterVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        return notifyPrivateLetterVO;
    }

    /**
     * 查询通知中心-用户私信列表
     * 
     * @param query 通知中心-用户私信
     * @return 通知中心-用户私信
     */
    @Override
    public List<NotifyPrivateLetterVO> selectNotifyPrivateLetterList(NotifyPrivateLetterQuery query)
    {
        return baseMapper.selectNotifyPrivateLetterList(query);
    }

    /**
     * 删除通知中心-用户私信信息
     * 
     * @param id 通知中心-用户私信主键
     * @return 结果
     */
    @Override
    public Integer deleteNotifyPrivateLetterById(String id)
    {
        NotifyPrivateLetterVO notifyPrivateLetterVO=baseMapper.selectNotifyPrivateLetterById(id);
        if(notifyPrivateLetterVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        return baseMapper.deleteNotifyPrivateLetterById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public Integer insertBatch(List<NotifyPrivateLetter> list) {
        return baseMapper.insertBatch(list);
    }

    @Override
    public Page<UserPrivateLetterVO> userPrivatePage(NotifyPrivateLetterQuery query) {
        String currUserId=query.getReceiverId();
        if(StringUtils.isBlank(currUserId)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"currUserId");
        }
        //获得Page对象
        Page<UserPrivateLetterVO> page = query.getPage();
        List<UserPrivateLetterVO> pageList=baseMapper.userPrivatePage(page,query);
        if(pageList!=null&&pageList.size()>0){
            List<String> userIds=new ArrayList<>();
            pageList.stream().forEach(privateLetterVO->{
                String senderId=privateLetterVO.getSenderId();
                String receiverId=privateLetterVO.getReceiverId();
                userIds.add(senderId);
                userIds.add(receiverId);
            });
            try {
                Future<Map<String, UserInfoVO>> taskA =asyncExecutor.submit(()->{
                    //批量查询用户信息
                    Map<String, UserInfoVO> userInfoMap=new HashMap<>();
                    try {
                        userInfoMap=userFeignClient.batchQuery(userIds);
                    }catch (Exception e){
                        log.info("query remote user info error");
                    }
                    return userInfoMap;
                });
                Map<String, UserInfoVO> finalUserInfoMap = taskA.get();
                pageList.stream().parallel().forEach(privateLetterVO->{
                    String senderId=privateLetterVO.getSenderId();
                    String receiverId=privateLetterVO.getReceiverId();
                    UserInfoVO senderInfo = finalUserInfoMap.get(senderId);
                    if(senderInfo!=null){
                        privateLetterVO.setSenderName(senderInfo.getUsername());
                        privateLetterVO.setSenderPhoto(senderInfo.getPhoto());
                    }
                    UserInfoVO receiverInfo = finalUserInfoMap.get(receiverId);
                    if(receiverInfo!=null){
                        privateLetterVO.setSenderName(receiverInfo.getUsername());
                        privateLetterVO.setSenderPhoto(receiverInfo.getPhoto());
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //循环遍历获取用户信息
        page.setRecords(pageList);
        return page;
    }
}
